<template>
  <mavon-editor :ref="refId"
                v-model="content"
                @change="parseHtml"
                @imgAdd="uploadImage"
                :autofocus="false">
  </mavon-editor>
</template>

<script>
import {mavonEditor} from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import {uploadFile} from "@/network/file";

export default {
  name: 'MarkdownEditor',
  components: {
    mavonEditor
  },
  props: {
    refId: {
      type: String,
      required: true
    },
    value: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      content: this.value,
      render: ''
    }
  },
  methods: {
    uploadImage: function (pos, imgFile) {
      let refId = this.refId
      if (imgFile.size > 5 * 1024 * 1024) {
        this.$refs[refId].$img2Url(pos, '')
        this.$message.warning('The maximum limit for uploading pictures is 5MB')
        return
      }
      let formData = new FormData()
      formData.append('file', imgFile)
      formData.append('use', FILE_USE.PROBLEM.key);
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
      });
      uploadFile(formData).then(res => {
        if (res.status===200) {
          this.$message.success("Image uploaded successfully")
          this.$refs[refId].$img2Url(pos, res.data)
        } else {
          this.$message.error(res.message)
          this.$refs[refId].$img2Url(pos, '')
        }
        loading.close()
      }).catch(_ => {
        console.log(_);
        this.$message.warning('Please re-upload again')
        this.$refs[refId].$img2Url(pos, '')
        loading.close()
      })
    },
    parseHtml: function (value, render) {
      this.render = render;
      this.$emit('input', value)
    }
  },
  watch: {
    value: function (value) {
      this.content = value
    }
  }
}
</script>

<style>

</style>
